<template>
  <div>
    <h3>用户列表</h3>
    <el-input
        placeholder="请输入用户名"
        v-model="searchQuery"
        style="width: 200px; margin-right: 10px;"
        clearable
        @clear="fetchUsers"
    />
    <el-button type="primary" @click="searchUsers">搜索</el-button>
    <el-button type="primary" @click="openDialog">新增用户</el-button>
    <el-table :data="users" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="username" label="用户名" width="180"></el-table-column>
      <el-table-column prop="phone" label="电话" width="180"></el-table-column>
      <el-table-column prop="lastLoginTime" label="上次登录时间" width="180"></el-table-column>
      <el-table-column label="操作" width="180">
        <template v-slot="scope">
          <el-button size="small" @click="editUser(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteUser(scope.row.username)">删除</el-button>
          <el-button size="small" type="primary" @click="upgradeToManager(scope.row.username)">升级为管理员</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="isEdit ? '编辑用户' : '添加用户'" v-model="dialogVisible">
      <el-form :model="newUser" :rules="rules" ref="userForm">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="newUser.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input type="password" v-model="newUser.password"></el-input>
          </el-form-item>
          <el-form-item label="电话" :label-width="formLabelWidth" prop="phone">
            <el-input v-model="newUser.phone"></el-input>
          </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addOrUpdateUser">确定</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      users: [],
      dialogVisible: false,
      isEdit: false,
      searchQuery: '',
      newUser: {
        username: '',
        password: '',
        phone: '',
        role: 'user', // 默认角色
        lastLoginTime: null
      },
      formLabelWidth: '120px',
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        phone: [{ required: false, message: '请输入电话', trigger: 'blur' }]
      }
    };
  },
  created() {
    this.fetchUsers();
  },
  methods: {
    fetchUsers() {
      axios.get('http://localhost:8081/api/auth/users')
          .then(response => {
            this.users = response.data;
          })
          .catch(error => {
            console.error("There was an error fetching the users!", error);
          });
    },
    searchUsers() {
      const params = { username: this.searchQuery };
      axios.get('http://localhost:8081/api/auth/users/search', { params })
          .then(response => {
            this.users = response.data;
          })
          .catch(error => {
            console.error("There was an error searching the users!", error);
          });
    },
    openDialog() {
      this.isEdit = false;
      this.dialogVisible = true;
      this.resetUser();
    },
    editUser(user) {
      this.isEdit = true;
      this.dialogVisible = true;
      this.newUser = { ...user };
    },
    addOrUpdateUser() {
      this.$refs.userForm.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            axios.put('http://localhost:8081/api/auth/update', this.newUser)
                .then(() => {
                  this.dialogVisible = false;
                  this.fetchUsers();
                  this.resetUser();
                  ElMessage.success('用户更新成功');
                })
                .catch(error => {
                  console.error("There was an error updating the user!", error);
                  ElMessage.error('用户更新失败');
                });
          } else {
            axios.post('http://localhost:8081/api/auth/register', this.newUser)
                .then(() => {
                  this.dialogVisible = false;
                  this.fetchUsers();
                  this.resetUser();
                  ElMessage.success('用户添加成功');
                })
                .catch(error => {
                  console.error("There was an error adding the user!", error);
                  ElMessage.error('用户添加失败');
                });
          }
        }
      });
    },
    deleteUser(username) {
      axios.delete(`http://localhost:8081/api/auth/delete/${username}`)
          .then(() => {
            this.fetchUsers();
            ElMessage.success('用户删除成功');
          })
          .catch(error => {
            console.error("There was an error deleting the user!", error);
            ElMessage.error('用户删除失败');
          });
    },
    upgradeToManager(username) {
      axios.put(`http://localhost:8081/api/auth/upgrade/${username}`)
          .then(() => {
            this.fetchUsers();
            ElMessage.success('用户已升级为管理员');
          })
          .catch(error => {
            console.error("There was an error upgrading the user!", error);
            ElMessage.error('升级失败');
          });
    },
    resetUser() {
      this.newUser = {
        username: '',
        password: '',
        phone: '',
        role: 'user', // 默认角色
        lastLoginTime: null
      };
    }
  }
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
